package ink.xiaobaibai.token;

import ink.xiaobaibai.common.MyRole;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: 小白白
 * @create: 2021-05-14
 **/

public class JWTAuthenticationToken extends AbstractAuthenticationToken {

    private static final long serialVersionUID = 522L;
    private String JWT;
    private String userNumber;
    private Integer userId;

    public JWTAuthenticationToken(String JWT) {
        super(null);
        this.JWT = JWT;

    }

    public JWTAuthenticationToken(Collection<? extends GrantedAuthority> authorities, String userNumber, Integer userId) {
        super(authorities);
        this.userNumber = userNumber;
        this.userId = userId;
    }

    public Integer getUserId() {
        return this.userId;
    }

    public String getRole() {
        for (GrantedAuthority authority : this.getAuthorities()) {
            if (authority.getAuthority().equals(MyRole.ADMIN)) {
                return MyRole.ADMIN;
            }
            if (authority.getAuthority().equals(MyRole.AGENT)) {
                return MyRole.AGENT;
            }
            if (authority.getAuthority().equals(MyRole.DISTRIBUTOR)) {
                return MyRole.DISTRIBUTOR;
            }
        }
        throw new RuntimeException("获取身份时未知错误");
    }

    public Set<String> getRoles() {
        return this.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
    }

    public String getJWT() {
        return this.JWT;
    }

    public String getUserNumber() {
        return this.userNumber;
    }

    @Override
    public Object getCredentials() {
        return this.userNumber;
    }

    @Override
    public Object getPrincipal() {
        return this.userNumber;
    }
}
